﻿/*
Copyright (c) Microsoft Corporation

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0   

THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.  

See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. 
*/

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509

var accelerometer = null;
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var nav = WinJS.Navigation;
    var hikerArr = [];
    var yeti = null;
    window.isMuted = false; // this will be accessed from both the game lib and the metro interface

    // color frame index key:
    // gray (#333) = 0
    // orange (#dc8000) = 1
    // green (#00c0ac) = 2
    // blue (#0096dc) = 3


    // base yeti object
    var defaultYeti = {
        title: 'Customize Your Yeti',
        frame: 0,
        id: "671750e8-bf16-4b11-8071-82902e955688",
        profile_pic: 'images/default_face.png',
        picture: 'media/yeti.png',
        color: '#c9b497',
        stats: {kills: 0, highscore: 0}
    };

    // default hikers list
    var defaultHikerArray = [
    {
        title: "+ Add a New Hiker", frame: 0, id: '82bff993-1d8f-4283-91b3-1c8f34a6a08e',
        isTemplate: true,
        profile_pic: '',
        picture: "images/climber_333333_big.png",
        compos_data_url: '',
        color: '#333333',
        stats: { deaths: 0, wins: 0 }
    },
    {
        title: "John Smith",
        frame: 1,
        id: '5fda9cc1-bbf4-4a52-b075-21e7728ab7a2',
        profile_pic: '',
        picture: "images/climber_dc8000_big.png",
        compos_data_url: '',
        color: '#dc8000',
        stats: { deaths: 0, wins: 0 }
    },
    {
        title: "John Smith",
        frame: 2,
        id: '26f40d-9cdd-4c03-a138-b75b9ed3c54f',
        profile_pic: '',
        picture: "images/climber_00c0ac_big.png",
        compos_data_url: '',
        color: '#00c0ac',
        stats: { deaths: 0, wins: 0 }
    },
    {
        title: "John Smith",
        frame: 3,
        id: '50fdb382-d8fb-4f22-9d90-a8902b215fa5',
        profile_pic: '',
        picture: "images/climber_0096dc_big.png",
        compos_data_url: '',
        color: '#0096dc',
        stats: { deaths: 0, wins: 0 }
    }
    ];

    // check local storage state
    if (hasHikerLocalStorageData()) {
        hikerArr = getHikerLocalStorage();
    } else {
        hikerArr = defaultHikerArray;
    };

    // check local storage state
    if (hasYetiLocalStorageData()) {
        yeti = getYetiLocalStorage();
    } else {
        yeti = defaultYeti;
    };

    var dataList = new WinJS.Binding.List(hikerArr);

    var filteredList = dataList.createFiltered(returnFiltered); // without the Template one

    var publicMembers =
    {
        itemList: dataList,
        filtered: filteredList
    };

    // create global namespaces for hikers and yeti
    WinJS.Namespace.define("DataHikers", publicMembers);
    WinJS.Namespace.define("DataYeti", {data: yeti});


    if (DataYeti.data.profile_pic == 'images/default_face.png') {
        getUserPic();
    };

    /* end start menu */

    var templateConversionFunctions = {
        hexColorToClass: WinJS.Binding.converter(function (color) {
            if (color) {
                var c = color.replace('#', '');
                return 'color_%'.replace('%', c);
            };
        })
    };
    WinJS.Namespace.define("TemplateConverterFunctions", { functions: templateConversionFunctions });

    // handle snapped view
    window.addEventListener('resize', function (e) {
        var viewStates = Windows.UI.ViewManagement.ApplicationViewState;
        var newViewState = Windows.UI.ViewManagement.ApplicationView.value;
        var body = document.getElementsByName('body')[0];
        if (newViewState === viewStates.snapped) {
            if (window.game) {
                window.game.isPaused = true;
            };
            var snapview_yeti_template = document.getElementById('snapview_yeti_data');
            var snappedview_hiker_list = document.getElementById('imageTextListLandingSnap');

            var yetiClone = window.clone(DataYeti.data);
            if (yetiClone.title == 'Customize Your Yeti') {
                yetiClone.title = 'Yeti';
            };
            WinJS.Binding.processAll(snapview_yeti_template, yetiClone);
            snappedview_hiker_list.winControl.forceLayout();
        };
    });



    WinJS.Navigation.addEventListener("navigated", function (eventObject) {
        var url = eventObject.detail.location;
        var host = document.getElementById("contentHost");
        // Call unload method on current scenario, if there is one
        host.winControl && host.winControl.unload && host.winControl.unload();
        WinJS.Utilities.empty(host);
        WinJS.UI.Pages.render(url, host, eventObject.detail.state).then(function () {
            var body = document.getElementsByTagName('body')[0];
            var location_class = url.match(/[a-z]+\.html/gi)[0].replace('.html','');
            body.setAttribute('id', location_class);
            WinJS.Application.sessionState.lastUrl = url;
        })
    });


    app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {

            if (accelerometer === null) {
                accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();

                if (accelerometer !== null) {
                    //accelerometer available on device
                    // Establish the report interval
                    var minimumReportInterval = accelerometer.minimumReportInterval;
                    var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
                    accelerometer.reportInterval = reportInterval;
                }
            }


            var audio_option = document.getElementById('audio_option');
            
            audio_option.addEventListener('change', function (e) {
                var wincontrol = this.winControl;
                var isChecked = wincontrol.checked;
                window.isMuted = !isChecked;
                if (typeof (game) != 'undefined' && (game.system)) {
                    if (window.isMuted) {
                        game.system.soundmanager.mute_all(false);
                    } else {
                        game.system.soundmanager.mute_all(true);
                    }
                };
            });

            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
            args.setPromise(WinJS.UI.processAll().then(function () {
                var url = '/home.html';
                return WinJS.Navigation.navigate(url);
            }));
        }
    });

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to 
        // complete an asynchronous operation before your application is 
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;

        args.setPromise(WinJS.UI.processAll().then(function (a) {
            // save to localStorage, update live tile on suspend
            saveYetiLocalStorage();
            saveHikerLocalStorage();
            Livetile.updateLiveTile();
        }));

    };

    // add settings option
    app.onsettings = function (e) {

        e.detail.applicationcommands = {
            "options": {title: "Game Options" }
        };
        var audio_option = document.getElementById('audio_option');
        audio_option.winControl.check = window.isMuted;
        WinJS.UI.SettingsFlyout.populateSettings(e);
    }

    app.start();

})();

function saveHikerLocalStorage() {
    var data = [];
    DataHikers.itemList.forEach(function (itm) {
        data.push(itm);
    });
    var json_string = JSON.stringify(data);
    window.localStorage.hikerData = json_string;
};

function getUserPic() {
    var userInformation = Windows.System.UserProfile.UserInformation;
    var userPic = userInformation.getAccountPicture(Windows.System.UserProfile.AccountPictureKind.smallImage);

    if (userPic) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var img = new Image();
        var imgurl = URL.createObjectURL(userPic, { oneTimeOnly: true });
        img.src = imgurl;

        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            var dataurl = canvas.toDataURL();
            DataYeti.data.profile_pic = dataurl;
            Livetile.updateLiveTile();
        };

    };
}

function saveYetiLocalStorage() {
    var data = DataYeti.data;
    if (typeof (data) == 'undefined') {
        return false;
    };
    var json_string = JSON.stringify(data);
    window.localStorage.yetiData = json_string;
};

function hasHikerLocalStorageData() {
    return (typeof (window.localStorage.hikerData) !== 'undefined');
};

function hasYetiLocalStorageData() {
    return (typeof (window.localStorage.yetiData) !== 'undefined');
};

function getHikerLocalStorage() {
    var hikerArray = JSON.parse(window.localStorage.hikerData);
    return hikerArray;
};

function getYetiLocalStorage() {
    var yetiData = JSON.parse(window.localStorage.yetiData);
    return yetiData;
};

function linkClickEventHandler(evt) {
    evt.preventDefault();
    var link = evt.target;
    var state = window[evt.target.getAttribute('data-state')] || {};
    WinJS.Navigation.navigate(link.href, state);
};

function makeNewHiker() {
    var new_id = newUUID();
    return {
        title: "Give me a name!",
        frame: 0,
        id: new_id,
        isTemplate: true,
        profile_pic: 'images/default_face.png',
        picture: "images/climber_333333_big.png",
        compos_data_url: '',
        color: '#333333',
        stats: { deaths: 0, wins: 0 }
    }
};

function newUUID() {
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });

    return uuid;
};


function returnFiltered(itm) {
    if (typeof (itm.isTemplate) == 'undefined' || !itm.isTemplate) {
        return true;
    } else {
        return false;
    }
};

function returnDataUrlFromImg(image) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = image.width;
    canvas.height = image.height;
    ctx.drawImage(image, 0, 0);
    var dataurl = canvas.toDataURL();
    return dataurl;
}

function returnBlobFromImg(image) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = image.width;
    canvas.height = image.height;
    ctx.drawImage(image, 0, 0);
    var blob = canvas.msToBlob();
    return blob;
}


function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}